<template>
    <div class="docEditor">
        <mavon-editor 
        :toolbars="editorToolBar"
        class="doc_edit"
        v-model="docContentEdited"
        ref=md
        @imgAdd="$imgAdd"
        @imgDel="$imgDel"
        >
            <!-- 左工具栏后加入自定义按钮  -->
            <template slot="left-toolbar-after">
            <button
            type="button"
            @click="saveEditoedContent"
            class="op-icon fa fa-mavon-floppy-o"
            aria-hidden="true"
            title="保存编辑内容"
            ></button>
            </template>
            <!-- 右工具栏前加入自定义按钮  -->
            <template slot="right-toolbar-before">
                <button
                type="button"
                @click="uploadDoc"
                class="el-icon-upload"
                aria-hidden="true"
                title="上传文档"
                background="../../assets/upload.png"
                ></button>
            </template>
        </mavon-editor>
    </div>

</template>

<script>

import axios from 'axios';

export default {    
    data(){
        return{
            editorToolBar: {
                bold: true, // 粗体
                italic: true, // 斜体
                header: true, // 标题
                underline: true, // 下划线
                strikethrough: true, // 中划线
                mark: true, // 标记
                superscript: true, // 上角标
                subscript: true, // 下角标
                quote: true, // 引用
                ol: true, // 有序列表
                ul: true, // 无序列表
                link: true, // 链接
                imagelink: true, // 图片链接
                code: true, // code
                table: true, // 表格
                fullscreen: true, // 全屏编辑
                readmodel: true, // 沉浸式阅读
                htmlcode: true, // 展示html源码
                help: true, // 帮助
                /* 1.3.5 */
                undo: true, // 上一步
                redo: true, // 下一步
                trash: true, // 清空
                /* 1.4.2 */
                navigation: true, // 导航目录
                /* 2.1.8 */
                alignleft: true, // 左对齐
                aligncenter: true, // 居中
                alignright: true, // 右对齐
                /* 2.2.1 */
                subfield: true, // 单双栏模式
                preview: true, // 预览
            },
            img_file:{},
            docName:'',
            docContentEdited:'',
            userId: 0,
        }
    },
    props:{
        archiveId: {
            type: Number, // 指定类型为数字
            required: true,
        },
        docId: {
            type: Number, // 指定类型为数字
            required: true,
        },
    },  
    created() {
        this.userId = localStorage.getItem('userId');
        //第一步，得到docList,由此得到doc的内容数据
        this.$axios.get('http://localhost:8001/doc/getUserArchiveDoc', {params: {
            userId:this.userId,
            archiveId:this.archiveId
        }}).then(res => {
            for(var doc_info of res.data){
                if(doc_info.docId==this.docId){
                    this.docName=doc_info.docName;
                    this.docContentEdited=doc_info.docContent;
                    break;
                }
            }
            console.log('Markdown文件内容获取成功');
            if(this.$root.docContentEditedSave.has(this.docId.toString())){
                this.docContentEdited=this.$root.docContentEditedSave.get(this.docId.toString());
                console.log('Markdown暂存内容获取成功');
            }else{
                console.log('未读取暂时保存的内容');
            }
        }).catch(err => {
            console.log(err);
            this.docContentPreview=err;
        });
        
    },
    computed:{
        
    },
    beforeRouteLeave(to, from, next) {
        if (from.path === this.$route.path) {
        const confirmLeave = window.confirm('未保存的编辑内容将舍弃，确定要离开吗？');
        if (confirmLeave) {
            next();
        } else {
            next(false);
        }
        } else {
        next();
        }
    },
    methods: {
        // 绑定@imgAdd event
        $imgAdd(pos, $file){
            // 缓存图片信息
            this.img_file[pos] = $file;
        },
        $imgDel(pos){
            delete this.img_file[pos];
        },
        saveEditoedContent(){
            if(this.$root.docContentEditedSave.has(this.docId.toString())){
                this.$root.docContentEditedSave.set(this.docId.toString(),this.docContentEdited);
                console.log('文件暂存成功1');
            }else{
                this.$root.docContentEditedSave.append(this.docId.toString(),this.docContentEdited);
                console.log('文件暂存成功2');
            }
        },
        uploadDoc(){

            // 第一步.设置上传图片的formdata.
            var formdata = new FormData();
            for(var _img in this.img_file){
                formdata.append('files', this.img_file[_img]);
            }

            //将关键符加入formData
            formdata.append('userId',this.userId);
            formdata.append('docName',this.docName);
            formdata.append('archiveId',this.archiveId);

            console.log(formdata.getAll('files'));
            //定义文件信息的json格式
            const documentDot = {
                "document":{
                "userId": this.userId,
                "docName":this.docName
                },
                "content":this.docContentEdited
            };

            

            //当没有新图片被添加时，直接更新文档
            if(!formdata.has('files')){
                console.log('文档内容即将开始更新1');
                let timeStamp = new Date();
                let ss = new Date(timeStamp).getSeconds() < 10 ? "0" + new Date(timeStamp).getSeconds() : new Date(timeStamp).getSeconds();
                let sss = new Date(timeStamp).getMilliseconds() < 10 ? "0" + new Date(timeStamp).getMilliseconds() : new Date(timeStamp).getMilliseconds();
                console.log("开始于"+ss+"分"+sss+"秒");
                axios({
                    url: 'http://localhost:8001/doc/updateDoc',
                    method: 'post',
                    data: {
                        "document":{
                        "userId": this.userId,
                        "docName":this.docName,
                        "archiveId":this.archiveId
                        },
                        "content":this.docContentEdited
                    },
                    }).then((res) => {
                        console.log('文档内容更新完毕');
                        //更新代表着未编辑的文档内容为最新
                        if(this.$root.docContentEditedSave.has(this.docId.toString())){
                            this.$root.docContentEditedSave.set(this.docId.toString(),this.docContentEdited);
                        }else{
                            this.$root.docContentEditedSave.append(this.docId.toString(),this.docContentEdited);
                        }
                        let timeStamp0 = new Date();
                        let ss0 = new Date(timeStamp0).getSeconds() < 10 ? "0" + new Date(timeStamp0).getSeconds() : new Date(timeStamp0).getSeconds();
                        let sss0 = new Date(timeStamp0).getMilliseconds() < 10 ? "0" + new Date(timeStamp0).getMilliseconds() : new Date(timeStamp0).getMilliseconds();
                        console.log("结束于"+ss0+"分"+sss0+"秒");
                    })
                    .catch(error=>{
                    console.log(error);
                })
            }else{
                //当有新的图片被添加时
                //第一次上传会上传图片信息
                //第二次上传会上传文档信息，    改用json了
                console.log('图片开始上传');
                let timeStamp1 = new Date();
                let ss1 = new Date(timeStamp1).getSeconds() < 10 ? "0" + new Date(timeStamp1).getSeconds() : new Date(timeStamp1).getSeconds();
                let sss1 = new Date(timeStamp1).getMilliseconds() < 10 ? "0" + new Date(timeStamp1).getMilliseconds() : new Date(timeStamp1).getMilliseconds();
                console.log("开始于"+ss1+"分"+sss1+"秒");
                axios({
                    url: 'http://localhost:8001/doc/uploadPic',
                    method: 'post',
                    data: formdata,
                    headers: { 'Content-Type': 'multipart/form-data' },
                }).then((res) => {
                    /**
                     * 例如：返回数据为 res = [[pos, url], [pos, url]...]
                     * pos 为原图片标志（0）
                     * url 为上传后图片的url地址
                     */
                    // 第二步.将返回的url替换到文本原位置![...](0) -> ![...](url)
                    for (const img of res.data) {
                        //console.log(imgData.id);
                        //console.log(imgData.url);
                        //img[0]代表着pos，而img[1]代表的为img在后端的URL地址
                        let imgUrl = img.url.toString().replace('127.0.0.1:','http://localhost:');
                        console.log(imgUrl);
                        this.$refs.md.$img2Url(img.id, imgUrl);
                        let timeStamp2 = new Date();
                        let ss2 = new Date(timeStamp2).getSeconds() < 10 ? "0" + new Date(timeStamp2).getSeconds() : new Date(timeStamp2).getSeconds();
                        let sss2 = new Date(timeStamp2).getMilliseconds() < 10 ? "0" + new Date(timeStamp2).getMilliseconds() : new Date(timeStamp2).getMilliseconds();
                        console.log("结束于"+ss2+"分"+sss2+"秒");
                    }     
                }).then(()=>{
                    // 第三步，将文本内容上传到服务器.
                    //将用户名，文件名，文件内容保存至formData
                    console.log('文档内容即将开始更新2');
                    let timeStamp3 = new Date();
                    let ss3 = new Date(timeStamp3).getSeconds() < 10 ? "0" + new Date(timeStamp3).getSeconds() : new Date(timeStamp3).getSeconds();
                    let sss3 = new Date(timeStamp3).getMilliseconds() < 10 ? "0" + new Date(timeStamp3).getMilliseconds() : new Date(timeStamp3).getMilliseconds();
                    console.log("开始于"+ss3+"分"+sss3+"秒");
                    axios({
                        url: 'http://localhost:8001/doc/updateDoc',
                        method: 'post',
                        data: {
                            "document":{
                            "userId": this.userId,
                            "docName":this.docName,
                            "archiveId":this.archiveId
                            },
                            "content":this.docContentEdited
                        },
                        }).then((res) => {
                            console.log('文档内容更新完毕');
                            //更新代表着未编辑的文档内容为最新
                            if(this.$root.docContentEditedSave.has(this.docId.toString())){
                                this.$root.docContentEditedSave.set(this.docId.toString(),this.docContentEdited);
                            }else{
                                this.$root.docContentEditedSave.append(this.docId.toString(),this.docContentEdited);
                            }
                            //window.location.reload();
                            let timeStamp4 = new Date();
                            let ss4 = new Date(timeStamp4).getSeconds() < 10 ? "0" + new Date(timeStamp4).getSeconds() : new Date(timeStamp4).getSeconds();
                            let sss4 = new Date(timeStamp4).getMilliseconds() < 10 ? "0" + new Date(timeStamp4).getMilliseconds() : new Date(timeStamp4).getMilliseconds();
                            console.log("结束于"+ss4+"分"+sss4+"秒");
                        })
                }).catch(error=>{
                    console.log(error);
                })
            }
        }
    }

}
</script>

<style>
.docEditor{
    position: fixed;
    left: 2%;
    right: 2%;
    width: 96%;
    height: 100%;
}
.doc_edit{
    height:88%;
    min-width: 100%;
}
</style>